﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI;

namespace Framework.Infrastructure
{
    public static class WebUtility
    {
        public static string StyledSheetEncode(string s)
        {
            s = s.Replace("\\", "\\\\").Replace("'", "\\'").Replace("\"", "\\\"").Replace("\r\n", "\\n").Replace("\n\r", "\\n").Replace("\r", "\\n").Replace("\n", "\\n");
            s = s.Replace("/", "\\/");
            return s;
        }

        public static void ShowMessage(this Page page, string message, bool close, string redirectUrl)
        {
            string msg = StyledSheetEncode(message);
            string script = @"<script language='javascript'>
    								function AlertMsg()
    								{
    									if(document.readyState=='complete')
    									{
    										alert('{0}');
    										{1}
    									}
    									else
    										setTimeout('AlertMsg()', 100);
    								}
    								AlertMsg();
    							</script>";
            script = script.Replace("{0}", message);
            if (redirectUrl != string.Empty)
            {
                script = script.Replace("{1}", "window.location.href = '" + redirectUrl + "';");
            }
            else
            {
                if (close)
                    script = script.Replace("{1}", "window.close();");
                else
                    script = script.Replace("{1}", string.Empty);
            }
            if (!page.ClientScript.IsStartupScriptRegistered("MsgScript"))
                page.ClientScript.RegisterStartupScript(page.GetType(), "MsgScript", script);
        }

        public static void ShowMessage(this Page page, string message)
        {
            ShowMessage(page, message, false, string.Empty);
        }
    }
}
